const FormData = require('form-data');
const fs = require('fs');
const config = require('./config');
const path = require('path');
const os = require('os');
const axios = require('axios');
const chalk = require('chalk');
const userName = os.hostname();
// 获取表单长度
function getLength(form){
  return new Promise((resolve, reject) => {
    form.getLength((b, s) => {
      resolve(s);
    });
  });
};
module.exports = async function (file){
  const form = new FormData();
  const stream = fs.createReadStream(file);
  form.append('site', config.fupload.site);
  form.append('action', 'pub');
  form.append('token', config.fupload.token);
  form.append('targetUrl', `${config.fupload.baseUrl}${path.relative(config.projectDist,file)}`);
  form.append('fname', stream);
  form.append('username', userName);
  const length = await getLength(form);
  await axios.post('http://fupload.woa.com/api/filedispatcher', form, {
    headers: { ...form.getHeaders(), ...{ 'Content-Length': length} },
  }).then(({data})=>{
    if (data.code === 0) {
      console.log(
        chalk.green('✓ '),
        chalk.cyan(file),
        chalk.green('=>'),
        `${chalk.cyan(data.url)}  ${new Date().toLocaleString()}`,
        chalk.green(data.msg),
      );
    } else {
      throw new Error(`✗ ${file} \t ${data.msg}`);
    }
  })
};